package com.taotao.search.dao.imp;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.springframework.stereotype.Repository;

import com.taotao.search.dao.SearchDao;
import com.taotao.search.pojo.Item;
import com.taotao.search.pojo.SearchResult;

@Repository
public class SearchDaoImp implements SearchDao {

    @Resource(name = "httpSolrServer")
    private SolrServer solrServer;

    @Override
    public SearchResult search(SolrQuery solrQuery) throws Exception {
        // 返回值对象
        SearchResult result = new SearchResult();
        QueryResponse queryResponse = solrServer.query(solrQuery);
        SolrDocumentList solrDocumentList = queryResponse.getResults();
        // 查询总数
        long recordCount = solrDocumentList.getNumFound();
        result.setRecordCount(recordCount);

        // 取高粱显示
        Map<String, Map<String, List<String>>> highlighting = queryResponse.getHighlighting();
        // 取商品列表
        List<Item> itemList = new ArrayList<>();
        for (SolrDocument solrDocument : solrDocumentList) {
            Item item = new Item();
            item.setId(String.valueOf(solrDocument.get("id")));
            item.setCategoryName(String.valueOf(solrDocument.get("item_category_name")));
            // 取高亮显示的结果
            List<String> list = highlighting.get(solrDocument.get("id")).get("item_title");
            String title = "";
            if (list != null && list.size() > 0) {
                title = list.get(0);
            } else {
                title = String.valueOf(solrDocument.get("item_title"));
            }
            item.setTitle(title);
            item.setImage(String.valueOf(solrDocument.get("item_image")));
            item.setPrice(Long.valueOf(String.valueOf(solrDocument.get("item_price"))));
            item.setSellPoint(String.valueOf(solrDocument.get("item_sell_point")));
            itemList.add(item);
        }
        result.setItemList(itemList);
        return result;
    }

}
